'use strict';
const crypto = require('crypto');

module.exports = app => {
  /**
   * 用户权限校验
   */
  return class auth extends app.Service {
    /**
     * 用户登录验证
     * @param {string} username - 用户
     * @param {string} password - 密码
     * @return {object} - 验证结果 {status: boolean, msg: string}
     */
    async login(username, password) {
      const { app, ctx } = this;
      const { nodeTable, roleTable, roleUserTable, userTable } = app.config.authConfig;
      const user = await app.knex(userTable).first('id', 'password').where({ username });
      if (!user) {
        return { status: false, msg: '用户不存在' };
      }
      const hashPWD = crypto.createHash('sha256').update(password).digest('hex');
      if (hashPWD !== user.password) {
        return { status: false, msg: '用户名或密码错误' };
      }
      const logintime = new Date();
      const loginip = ctx.ip;
      await app.knex(userTable).update({ logintime, loginip }).where({ username });
      let role = await app.knex(roleUserTable).column('role_name').where({uid: user.id});
      role = role.map(val => val.role_name);
      const node = await app.knex(nodeTable).column('name', 'description', 'route', 'method').whereIn('role_name', role);
      app.redis.get('cache').set(user.id, JSON.stringify(node));
      return { status: true, msg: `${user.id}` };
    }
    /**
     * 用户登录验证
     * @param {string} uid - 用户ID
     * @return {object} - 验证结果 {status: boolean, msg: string}
     */
    async getUserAuth(uid) {
      const { app, ctx } = this;
      const userAuth = JSON.parse(await app.redis.get('cache').get(uid));
      return { status: true, msg: `${uid}` };
    }
  };
};
